﻿$.dialog.setConfig({'base':'http://www.huimg.cn/lib/dialog', skin:'bluebox'});
var edit_category_view_id = 'edit_category_view_id';
var msg_view_mod = '<span style="color:red;display:block;margin-top:15px;">[msg]</span>';
$(document).ready(function() {
	//textarea的id
	var contentId = 'content';
	var content_obj = $('#'+contentId);
	//替换原来div标题形式标签
	content_obj.val(buttonEvent_util.replace_h2(content_obj.val()));
	$.editor({
		id: 'text',
		contentId: contentId,
		toolbar: [
			'Preview','Save','Undo','Redo','Cut','Copy','Paste',
			'FontSize','Bold','ForeColor','JustifyLeft','H1',
			'BaikeLink','Link','HdImage','MultiImage',
			'Video','InsertTable','SpecialChar','Code','Source'
		],
		basePath: './static/js/jqeditor',
		plugin : baike_edit_util.getPluginSettings()
	});
	$('#tag_tip').click(function(){$('#share').toggle(); return false;});
	$($('#share')).click(function(){$(this).hide()});
	//参考资料需要的绑定。
	$('#referencediv > dl').find('a').click(function(e){
		var thisdl = $(this).closest('dl');
		var content = $(this).html();
		if(content=='编辑'){
			referre.edit(thisdl);
		}else if(content=='删除'){
			referre.remove(thisdl);
		}
	});
	$('#reference_edit').click(function(e){
		referre.add();
	});
	$('#reference_cancel').click(function(e){
		referre.init();
	});
	referre.init();
	$('#reference_name').focus(function(e){
		referre.inputclick($(this),'isname');
	});
	$('#reference_url').focus(function(e){
		referre.inputclick($(this),'isurl');
	});

	$('#referencediv').children('dl').hover(
		function () {
			$(this).children().last().show();
		},
		function () {
			$(this).children().last().hide();
		}
	);
	//修改分类事件绑定
	$("#edit_category").click(function() {
		baike_edit_util.edit_category();
	});
	//启动自动保存草稿定时器
	baike_edit_util.saveDraftsIntervalID = setInterval(function(){
		baike_edit_util.saveDrafts(false);
	},baike_edit_util.saveDraftsTime);
});

var baike_edit_util = {
	//保证ajax请求单例运行
	isBusy : false,
	//保存草稿间隔时间
	saveDraftsTime : 60000,
	//上次保存草稿后草稿摘要信息
	cache : {},
	saveDraftsIntervalID : null,
	/*
		存草稿方法
		isTips : 标志是否是手动点击，手动点击需要弹出提示
	*/
	saveDrafts : function(isTips){
		var self = this;
		var cache = self.cache ,
			content = jQEditor.getHTML(),//获取内容
			summary = $.trim($('#summary').val()),
			title = $.trim($("[name=title]").val()),
			reference = buttonEvent_util.getReference(),
			original = $("[name=original]:checked").val(),
			tag = [],
			summary_max = 400,
			error_msg = null,
			dialog = null;
		$('[name=tag[]]').each(function(){
			var val = $.trim($(this).val()) ;
			if(val.length){
				tag.push(buttonEvent_util.cut_str( val, 8));
			}
		});
		tag = tag.join(";") ;
		content = $.trim(content) ;
		if(title.length <1){
			error_msg = '标题不能为空。';
		}else if(content == '' || content == '<p>&nbsp;</p>' || content == '<br />') {
			error_msg = '内容不能为空。';
		}else if(summary.replace(/[^\x00-\xff]/g, "**").length>summary_max) {
			if(isTips){
				error_msg = '摘要不能超过'+parseInt(summary_max/2)+'个汉字。';
			}else{
				summary = buttonEvent_util.cut_str(summary , summary_max);
			}
		}else if(cache.title == title && 
			cache.content == content && 
			cache.summary == summary && 
			cache.reference == reference &&
			cache.original == original &&
			cache.tag == tag &&
			!isTips){
			return ;
		}else if(self.isBusy){
			error_msg = "系统繁忙，请稍后再试..";
		}else{
			self.isBusy = true;
		}
		if(error_msg) {
			if(isTips){
				self.dialog({
					content: msg_view_mod.replace('[msg]',error_msg),
					textCancel:'关闭',
					onCancel:function(){$.dialog.close(edit_category_view_id);}
				});
			}
			self.isBusy = false;
			return ;
		}else{
			if(isTips){
				dialog = self.dialog({
					content: msg_view_mod.replace('[msg]','正在保存。。。'),
					textCancel:'关闭',
					onCancel:function(){$.dialog.close(edit_category_view_id);}
				});
			}
		}
		var data = {
			content : content , 
			summary : summary , 
			title : title , 
			reference : reference , 
			original : original ,
			tag : tag
		} ;
		$.ajax({
			url : "/memcp.php?m=article&a=savedrafts&baike_id="+$("[name=baike_id]").val()+"&article_id="+$("[name=id]").val(),
			data : data,
			type: 'post',
			dataType: 'json',
			success : function(dt){
				self.cache = data ;
				var show_time = $("[name=save_drafts_date]");
				var date = new Date();
				date = date.getHours()+"时"+date.getMinutes()+"分";
				var msg = "当前内容已在"+date+"被保存到草稿箱。";
				if(isTips){
					if(dt.data && !dt.data.error){
						dialog.find('.content span').text('保存成功!');
						show_time.text(msg);
					}else if(dt.error){
						dialog.find('.content span').text(dt.error);
					}else{
						dialog.find('.content span').text('保存失败!');
					}
				}else{
					if(dt.data && !dt.data.error){
						show_time.text(msg);
					}
				}
			},
			error: function(XMLHttpRequest, status){
				if(isTips){
					dialog.find('.content span').text('保存草稿失败！');
				}
			},
			complete: function(XMLHttpRequest, status){
				self.isBusy = false;
			}
		});
	},
	publishDoc : function(){//发布操作
		var self = this;
		$('#content').val(jQEditor.getHTML());//编辑器中的内容更新到 content 文本域以待提交
		//参考资料拷贝过来。
		var dialog = null,error_msg = null;
		$('#reference').val(buttonEvent_util.getReference());
		$.ajax({
			type: 'POST',
			url: $('#editform').attr('action'),
			data: $('#editform').serialize()+'&in_ajax=1&datatype=json',
			beforeSend: function() {
				//这儿执行一些简单的数据验证
				var content = jQEditor.getHTML(),
					summarylen = $.trim(($('#summary').val())).replace(/[^\x00-\xff]/g, "**").length,
					original = $('[name = original]:checked').val(),
					tags = $("#tags input"),
					referencelen = $.trim(($('#reference').val())).replace(/[^\x00-\xff]/g, "**").length;;
				if(content == '' || content == '<p>&nbsp;</p>' || content == '<br />'){
					error_msg = '内容不能为空。'
				}else if(summarylen > 400) {
					error_msg = '摘要不能超过200个汉字。';
				}else if(referencelen > 2000) {
					error_msg = '参考资料不能超过1000个汉字。';
				}else if(original === 0 && $.trim($('#reference').val()) == '') {
					error_msg = '如果选择非原创，那么参考资料属于必填项。';
				}else {
					for(var i = 0; i < tags.length; i++) {
						var taglen = $.trim($(tags.get(i)).val()).replace(/[^\x00-\xff]/g, "**").length;
						if(taglen > 16) {
							error_msg = '每个标签不能超过8个汉字。';
							break ;
						}
					}
				}
				if(error_msg) {
					self.dialog({
						content:msg_view_mod.replace('[msg]',error_msg),
						textCancel : '关闭',
						onCancel:function(){$.dialog.close(edit_category_view_id);}
					});
					return false;
				}else{
					dialog = self.dialog({
						content:msg_view_mod.replace('[msg]','正在发布...'),
						textOk : '确定',
						onOk:function(){$.dialog.close(edit_category_view_id);}
					});
					return true;
				}
			},
			success: function(data, status) {
				if (typeof(data.status) == 'number' && data.status == 1) {
					//这里加入取消页面调整监控
					jQEditor.mod('Confirm').clear();
					location.href = data.forward;
				} else {
					dialog.find('.content span').text(data.msg);
				}
				return false;
			},
			dataType: 'json'
		});
	},
	exitEditDoc : function(){//退出操作
		var pb_msg='是否放弃对该文章的编辑？';
		if (confirm(pb_msg)) {
			window.location = $('#forward').val();
		}
	},
	//修改分类
	edit_category : function() {
		var self= this,
			baikeId = $('#baike_id').val(),
			html='<li><div class="edit_category_view">\
						修改分类：<span id="category_selectors"><input type="hidden" name="category" id="category"></span>\
					</div></li>',
					dialog_config = {
						content: html,
						title: '修改分类',
						onOk: function(dialog){
							var last_selector = $('#category_selectors select[up='+$('#category').val()+']');
							if (last_selector.css('display') == 'block' || last_selector.css('display') == 'inline' || last_selector.css('display') == 'inline-block') {
								alert('请选择最终分类，或取消。');
								return false;
							} else {
								var newCategoryId = params = $('#category').val().split('|')[1];
								$('#category_id').val(newCategoryId);
								for(var i in categoryData[baikeId]) {
									if(newCategoryId == categoryData[baikeId][i]['id']) {
										$('#category_name').text(categoryData[baikeId][i]['category_name']);
									}
								}
							}
							$.dialog.close(edit_category_view_id);
						},
						callback: function() {
							get_select($('#category_selectors'), baikeId + '|0', 'category', '',  0, null, 1000, getCategoryOptions); //getCategoryOptions 位于 common.js 中
						}
					};
		self.dialog(dialog_config);
	},
	dialog : function(parms) {
		var config = {
			id:edit_category_view_id,
			position:'c',
			overlay:1,
			fixed:1,
			textCancel : '关闭',
			width:300,
			height:120,
			offsetY:-90,
			title:'提示',
			content:'',
			resizable:0,
			onClose : function(dialog){
				dialog.find('.content').html("");
			}
		};
		$.extend(config, parms);
		return $.dialog(config);
	},
	//初始化图片上传组件settings参数设置
	getPluginSettings : function(){
		var self= this,
			settings = {
			HdImage: {
				settings: {
					getFileAction : function() {
						return self.getFileAction();
					},
					getUrlAction : function() {
						return self.getUrlAction();
					}
				}
			}
		};
		return settings;
	},
	//返回图片上传表单相关接口信息
	getFileAction : function(){
		var url = "http://a5.att.hudong.com/",
			doctitle = $('#_doc_title').length ? $('#_doc_title').val() : '',
			iden = $('#curuser_iden').length ? $('#curuser_iden').val() : '',
			art_iden=$('#art_iden').length ? $('#art_iden').val() : '',
			type = $('#type').val() == 19? 19: 14;//[14]主站文章=14，小百科19
		url += 'uploadFileNew.wiki?curuser_iden=' + iden + '&doc_title=' + encodeURI(doctitle) + '&art_iden=' + art_iden;
		url += '&type=' + type;
		url += '&host=' + encodeURIComponent('http://' + location.hostname + '/index.php?m=attachment&a=upload_article_img');
		return url;
	},
	//返回url图片上传表单相关接口信息
	getUrlAction : function(){
		var url = "http://a5.att.hudong.com/",
			doctitle = $('#_doc_title').length ? $('#_doc_title').val() : '',
			iden = $('#curuser_iden').length ? $('#curuser_iden').val() : '',
			art_iden=$('#art_iden').length ? $('#art_iden').val() : '',
			type = $('#type').val() == 19? 19: 14;//[14]主站文章=14，小百科19
		url +='uploadUrl.wiki?curuser_iden='+iden+'&doc_title='+encodeURI(doctitle);
		url += '&type=' + type;
		url += '&host=' + encodeURIComponent('http://' + location.hostname + '/index.php?m=attachment&a=upload_article_img');
		return url;
	}
}

var referre = {
	isname : 0,
	isurl : 0,
	referre_max_size : 2000 ,
	referre_name_len : 100 ,
	referre_url_len : 200 ,
	edit : function(thisdl){
		var self = this;
		var name = thisdl.children('dt').children('span').html(), 
			url = thisdl.children('dd').first().html(),
			key = thisdl.attr('id').split('_')[1];
			self.isname = self.isurl = 1;
			$('#reference_key').val(key);
			$('#reference_name').val(name).css("color","");
			$('#reference_url').val(url).css("color","");
			$('#reference_edit').val('编辑');
	},
	remove : function(thisdl){
		thisdl.remove();
	},
	add : function(){
		var key = $('#reference_key').val(),
			name = '',
			url = '',
			self = this;
		if(self.isname){
			name = $.trim($('#reference_name').val());
		}
		if(self.isurl){
			url = $.trim($('#reference_url').val());
		}
		$('#alert_name').html('');
		$('#alert_url').html('');
		var referre_size = parseInt(self.referre_max_size/(self.referre_name_len+self.referre_url_len)) ;
		if($("#referencediv").children("dl").length>=referre_size){
			$('#alert_name').html('参考资不能超过'+referre_size+'条');
			return false ;
		}
		if(name == ''){
			$('#alert_name').html('参考资料名称为必填项');
			return false;
		}
		if(url != ''){
			if(/^http:\/\/(\w+\.)+\w+/.test(url)==false){
				$('#alert_url').html('参考资料URL必需为以http://开头的网址');
				return false;
			}
		}
		name = buttonEvent_util.cut_str(name , self.referre_name_len) ;
		url = buttonEvent_util.cut_str(url , self.referre_url_len) ;
		if(+key>0){
			var thisdl = $('#dl_'+key);
			thisdl.children('dt').children('span').html(name);
			thisdl.children('dd').first().html(url);
		}else{
			var lastdl_id = $('#referencediv').children('dl').last().attr('id'),
				my_key = (lastdl_id == undefined ? 0 : +lastdl_id.split('_')[1])+1,
				my_class = (my_key%2) ? '' : 'class="ycwz_dlbg"',
				content = '<dl '+my_class+' id="dl_'+my_key+'">\
				<dt><strong>'+my_key+'.</strong><span>'+name+'</span></dt>\
				<dd>'+url+'</dd>\
				<dd style="display:none"><a href="javascript:void(0)">编辑</a>|<a href="javascript:void(0)">删除</a></dd>\
				</dl>';
			$('#referencediv').append(content);
			self.initdl($('#referencediv').children('dl').last());
		}
		self.init();
	},
	init : function(){
		var defaultname = '可以是书籍、文献，或网站的名称。',
			defaulturl = '请填写详细网址，以 http:// 开头',
			self = this;
			self.isname = self.isurl = 0;
		$('#reference_name').val(defaultname).css("color","gray");
		$('#reference_url').val(defaulturl).css("color","gray");
		$('#reference_key').val('');
		$('#reference_edit').val('添加');
	},
	inputclick : function(that,is){
		if(this[is] == 1) return false;
		that.css("color","").val('');
		this[is] = 1;
	},
	initdl : function(that){
		that.hover(
			function () {
				$(this).children().last().show();
			},
			function () {
				$(this).children().last().hide();
			}
		).find('a').click(function(e){
			var thisdl = $(this).closest('dl');
			var content = $(this).html();
			if(content=='编辑'){
				referre.edit(thisdl);
			}else if(content=='删除'){
				referre.remove(thisdl);
			}
		});
	}
};

var buttonEvent_util = {
	/*
		@string str : 被截的字符
		@int len ： 截取长度
	*/
	cut_str : function(str , len) {
		var cut_str = str ;
		for(var i = 0,j=0 ; i < cut_str.length ; i++){
			if(/[^\x00-\xff]/.test(cut_str.charAt(i))){
				j+=2;
			}else{
				j+=1;
			}
			if(j >=len){
				cut_str = cut_str.substring(0,i);
				break;
			}
		}
		return cut_str ;
	} ,
	//获取参考资料内容
	getReference : function() {
		var alldl = $('#referencediv').children('dl'),referre_val = '';
		if(alldl.length > 0){
			alldl.each(function(index, domEle){
			  var name = $.trim($(domEle).children('dt').children('span').html()), url = $.trim($(domEle).children('dd').first().html());
			  referre_val += name+'\n';
			  if(url){
				referre_val += url+'\n';
			  }
			  referre_val += '\n';
			});
		}
		return referre_val ;
	},
	//将原来<div class=hdwiki_tmml>的标签替换为h2
	replace_h2 : function(str){
		if($.trim(str).length<1)return str;
		var reg_v = /<div\s+class=\"?hdwiki_tmml\"?>([^<]+)<\/div>/ig;
		return str.replace(reg_v, '<h2>$1</h2>');
	}
}